package StudyCode.summary.csv;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CSVContentFormatter {
	private static final char DEFAULT_CSV_SEPARATOR = ';';
	private static final String DEFAULT_LINE_SEPARATOR = "\r\n";

	public static <T extends Object> InputStream formatCsv(
			List<List<T>> csvList) {
		return formatCsv(csvList, DEFAULT_CSV_SEPARATOR);
	}

	public static <T extends Object> InputStream formatCsv(
			List<List<T>> csvList, char csvSeparator) {


		StringBuilder csvContent = new StringBuilder();

		for (List<T> csvRecord : csvList) {
			if (csvRecord != null) {
				csvContent.append(formatCsvRecord(csvRecord, csvSeparator));
			}

			csvContent.append(DEFAULT_LINE_SEPARATOR);
		}

		return new ByteArrayInputStream(csvContent.toString().getBytes());
	}


	private static <T extends Object> String formatCsvRecord(
			List<T> csvRecord, char csvSeparator) {


		StringBuilder fields = new StringBuilder();
		String separator = String.valueOf(csvSeparator);

		for (Iterator<T> iter = csvRecord.iterator(); iter.hasNext(); ) {
			T object = iter.next();

			if (object != null) {
				String field = object.toString().replace("\"", "\"\""); // Escape quotes.

				if (field.contains(separator) || field.contains("\"")) {
					field = "\"" + field + "\"";
				}

				fields.append(field);
			}

			if (iter.hasNext()) {
				fields.append(separator);
			}
		}

		return fields.toString();
	}
}
